package tasks;

import java.util.ArrayList;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;

import core.Executor;
import core.Peer;
import core.Torrent;
import core.TorrentManager;

public class ContactTrackers implements Runnable {
	private Torrent torrent;
	private ArrayList<String> trackers;

	public ContactTrackers(ArrayList<String> trackers, Torrent torrent) {
		this.trackers = trackers;
		this.torrent = torrent;
	}

	@Override
	public void run() {
		CompletionService<ArrayList<Peer>> pool = new ExecutorCompletionService<ArrayList<Peer>>(Executor.getThreadPool());

		ArrayList<Peer> newPeers = null;

		for(int i=0; i<this.trackers.size(); i++) {
			pool.submit(new RequestTracker(this.trackers.get(i), this.torrent));
		}		

		Executor.getThreadPool().execute(new ContactPeer(this.torrent));
		
		for(int i=0; i <this.trackers.size(); i++){
			try {
				newPeers = pool.take().get();	
				
				if(newPeers != null) {
					TorrentManager.getInstance().addPeersByTorrent(this.torrent.getHashInfo(), newPeers);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}		
				
		
	}

}
